import { _decorator, Animation, Component, Node, Vec3 } from 'cc';
import MathUtil from '../util/MathUtil';
import BattleUnit from '../BattleUnit';
const { ccclass, property } = _decorator;

@ccclass('BattleUnitShow')
/**战斗单位显示 */
export class BattleUnitShow extends Component {
    private animation: Animation
    private data: BattleUnit;
    private targetPoint: Vec3;
    private moveCallback: Function;
    private attackCallback: Function;
    private attackEnd: Function;
    private growPos: Vec3;//初始位置
    private _dic: number;
    init(data: BattleUnit) {
        this.data = data;
        this.growPos = new Vec3(data.pos.x, data.pos.y, 0);
        this.setDic(this.data.dic);
    }

    protected onLoad(): void {
        this.animation = this.node.getComponent(Animation);
    }

    playAnimation(name: string) {
        this.animation.play(name);
    }

    protected update(dt: number): void {
        if (this.targetPoint) {
            if (MathUtil.distance2D(this.node.position, this.targetPoint) <= 0.5) {
                //移动到了目标点
                this.stopMove();
                this.moveCallback.call(null);
            } else {
                //往目标点移动
                this.node.setPosition(new Vec3(this.node.position.x + this._dic * 5, this.node.position.y, 0))
            }
        }
    }

    /**移动到某个点 */
    public moveTo(point: Vec3, callback: Function) {
        this.animation.play("run")
        this.targetPoint = point;
        this.moveCallback = callback;
        //设置朝向
        this.setDic(MathUtil.toOne(this.targetPoint.x - this.node.position.x));
    }

    /**移动回出生点 */
    public moveBack(callBack: Function): void {
        this.moveTo(this.growPos, () => {
            this.setDic(this.data.dic);
            callBack.call(null);
        })
    }

    /**停止移动(重新设置一下朝向) */
    public stopMove(): void {
        this.targetPoint = null;
        this.animation.play("stand");
    }

    /**攻击 */
    public doAtk(callback: Function, attackEnd: Function): void {
        this.animation.play("attack");
        this.attackCallback = callback;
        this.attackEnd = attackEnd;
    }

    /**触发动画事件攻击开始 */
    public onAttackStart(): void {

    }

    /**触发动画事件伤害计算 */
    public damage(): void {
        this.attackCallback.call(null);
    }

    /**触发动画事件攻击结束 */
    public onAttackEnd(): void {
        this.attackEnd.call(null);
    }

    /**受击 */
    public beHurt(damage: number) {

    }

    /**设置朝向 */
    public setDic(dic: number): void {
        this._dic = dic;
        this.node.setScale(new Vec3(dic, 1, 1));
    }
}


